<script setup lang="ts">
import { getCategoryTree } from '@/api/category'
import { ElMessage } from 'element-plus'
import { onMounted, ref, watch } from 'vue'

const sendCategoryId = defineEmits(['sendCategoryId'])

const dataSource = ref([])
const level1 = ref([])
const level2 = ref([])
const level3 = ref([])

defineExpose({
  level3
})

onMounted(async () => {
  const result = await getCategoryTree()
  if (result.code == 200) {
    dataSource.value = result.data
    level1.value = dataSource.value.filter((item) => item.level == 1)
  } else {
    ElMessage.error('查询分类数据失败')
  }
})

const valueSelect = ref('')

// 一级分类选择后，加载二级分类
watch(valueSelect, async (newValue) => {
  if (newValue) {
    const selectedLevel1 = dataSource.value.find((item) => item.name === newValue)
    if (selectedLevel1 && selectedLevel1.child.length > 0) {
      level2.value = selectedLevel1.child
    } else {
      level2.value = []
    }
  }
})

const valueSelect2 = ref('')
// 二级分类选择后，加载三级分类
watch(valueSelect2, async (newValue) => {
  if (newValue) {
    const selectedLevel2 = level2.value.find((item) => item.name === newValue)
    if (selectedLevel2 && selectedLevel2.child.length > 0) {
      level3.value = selectedLevel2.child
    } else {
      level3.value = []
    }
  }
})

const valueSelect3 = ref('')
//监听valueSelect3，发送给父组件
watch(valueSelect3, (newValue) => {
  //从level3中获取newValue对应的数据
  const selectedLevel3 = level3.value.find((item) => item.name === newValue)
  sendCategoryId('sendCategoryId', selectedLevel3.id)
})
</script>

<template>
  <div>
    <!-- 分类头 -->
    <el-card>
      <!-- <el-button type="primary" class="add_category" @click="addCategory">新增分类</el-button> -->
      <el-form :inline="true">
        <!-- 一级分类 -->
        <el-form-item label="一级分类" style="width: 27%">
          <el-select v-model="valueSelect" placeholder="一级分类" size="large" style="width: 240px">
            <el-option v-for="item in level1" :key="item.id" :value="item.name">{{
              item.name
            }}</el-option>
          </el-select>
        </el-form-item>
        <!-- 二级分类 -->
        <el-form-item label="二级分类" style="width: 27%">
          <el-select
            v-model="valueSelect2"
            placeholder="二级分类"
            size="large"
            style="width: 240px"
          >
            <el-option v-for="item in level2" :key="item.id" :value="item.name">{{
              item.name
            }}</el-option>
          </el-select>
        </el-form-item>
        <!-- 三级分类 -->
        <el-form-item label="三级分类" style="width: 27%">
          <el-select
            v-model="valueSelect3"
            placeholder="三级分类"
            size="large"
            style="width: 240px"
          >
            <el-option v-for="item in level3" :key="item.id" :value="item.name">{{
              item.name
            }}</el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss"></style>
